package com.sky.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class EasyExcelUtil {

    /**
     * 导入
     * @param httpServletResponse
     * @param list
     * @param clazz
     * @param <T>
     */
    public static <T> void export(HttpServletResponse httpServletResponse, List<T> list,Class<T> clazz) {
        ServletOutputStream out = null;
        try {
            out = httpServletResponse.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelWriterBuilder builder = new ExcelWriterBuilder();
        builder.file(out).excelType(ExcelTypeEnum.XLSX).autoCloseStream(true).head(clazz);
        ExcelWriter writer = builder.build();
        WriteSheet sheet = EasyExcel.writerSheet().build();
        writer.write(list, sheet);
        httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        try {
            httpServletResponse.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(".xlsx", "UTF-8"));
            httpServletResponse.setHeader("Pragma", "public");
            httpServletResponse.setHeader("Cache-Control", "no-store");
            httpServletResponse.addHeader("Cache-Control", "max-age=0");
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.finish();
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导入
     * @param file
     * @param clazz
     * @return
     * @param <T>
     * @throws IOException
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) throws IOException {
        // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
        // 具体需要返回多少行可以在`PageReadListener`的构造函数设置
        InputStream inputStream = file.getInputStream();
        List<T> list  = new ArrayList<>();
        EasyExcel.read(inputStream, clazz, new PageReadListener<T>(list::addAll)).sheet().doRead();
        return list;
    }

}
